import { User } from './../pages/initialization/viewmodel';
import { AdsAbout } from './order';
import { Injectable } from '@angular/core';
import { Headers, Http, Jsonp } from '@angular/http';
import 'rxjs/add/operator/toPromise';

declare let EventRegistHandle: any;
@Injectable()
export class ServiceBase {
    constructor() {
    }

    get SSL(): boolean { return location.protocol.indexOf("https") > -1; }
    get Host(): string {
        // let ip = this.HostIp;
        // let r = "http://" + ip;
        // if (this.SSL) r = "https://" + ip;
        // return r;
        return "https://172.16.255.145"
    }
    get HostIp(): string {
        if (this.LDCConfig) return this.LDCConfig.host;
        else return "localhost";
    }
    get Port(): number { return this.SSL ? 8886 : 8887; }
    get HostName(): string { return this.Host + ":" + this.Port + "/"; }
    get CloudHost(): string {
        // return "http://172.16.254.146";
        return "http://192.168.1.222";
    }
    get CloudPort(): number { return 9090; }
    get CloudHostName(): string { return this.CloudHost + ":" + this.CloudPort + "/"; }
    set adsAbout(adsAbout: AdsAbout) {
        localStorage.setItem("adsAbout", JSON.stringify(adsAbout));
    }
    get adsAbout(): AdsAbout {
        let adsAbout = localStorage.getItem("adsAbout");
        if (adsAbout) {
            return JSON.parse(adsAbout);
        }
        return null;
    }
    set currentDevice(currentDevice: any) {
        localStorage.setItem("currentDevice", JSON.stringify(currentDevice));
    }
    get currentDevice(): any {
        let currentDevice = localStorage.getItem("currentDevice");
        if (currentDevice) {
            return JSON.parse(currentDevice);
        }
        return null;
    }
    set currentKitchenSolutions(currentKitchenSolutions: any) {
        localStorage.setItem("currentKitchenSolutions", JSON.stringify(currentKitchenSolutions));
    }
    get currentKitchenSolutions(): any {
        let currentKitchenSolutions = localStorage.getItem("currentKitchenSolutions");
        if (currentKitchenSolutions) {
            return JSON.parse(currentKitchenSolutions);
        }
        return null;
    }
    set CurrentStore(store: any) {
        localStorage.setItem("store", JSON.stringify(store));
    }
    get CurrentStore(): any {
        let store = localStorage.getItem("store");
        if (store) {
            return JSON.parse(store);
        }
        return null;
    }
    /**
     * 当前店长用户
     */
    set StoreUser(value) {
        localStorage.setItem("user", JSON.stringify(value));
    };
    /**
     * 当前店长用户
     */
    get StoreUser() {
        let r = localStorage.getItem("user");
        if (r) return JSON.parse(r);
        return null;
    }
    set Token(value) {
        localStorage.setItem("token", value);
    }
    get Token() {
        return localStorage.getItem("token");
    }

    set Terminal(value) {
        localStorage.setItem("terminal", JSON.stringify(value));
    }
    get Terminal() {
        let terminal = localStorage.getItem("terminal");
        if (terminal) {
            return JSON.parse(terminal);
        } else {
            return null;
        }
    }

    //当前店员用户
    get CurrentUser(): { id: string, name: string } {
        return this.StoreUser.user;
    }

    set CurrentUser(user) {

    }

    get LDCConfig() {
        let config = localStorage.getItem("ldcconfig");
        if (config) {
            return JSON.parse(config);
        }
        return null;
    }
    set LDCConfig(value) {
        localStorage.setItem("ldcconfig", JSON.stringify(value));
    }

    protected http: Http;
    protected jsonp: Jsonp;

    /**
     * 
     * @param url 请求地址
     * @param params
     * @param sucb
     * @param errcb
     */
    protected Post(url: string, params) {
        // url = this.HostName + url;
        let headers = new Headers();
        this.CurrentStore && headers.append("storeId", this.CurrentStore.id);
        // debugger
        // this.StoreUser && headers.append("user", JSON.stringify({ id: this.StoreUser.user.id, name: this.StoreUser.user.name }));
        return this.doPost(url, params, headers);
    }
    private get fbsHost() {
        const ip = this.LDCConfig && this.LDCConfig.ip;
        const protocol = this.SSL ? "https://" : "http://";
        return protocol + ip;
    }
    private get fbsPort() {
        return this.SSL ? 8886 : 8887;
    }
    private get fbsAddress() {
        return this.fbsHost + ":" + this.fbsPort;
    }
    protected getOfFBS(url) {
        const newUrl = this.fbsAddress + url;
        return this.Get(newUrl);
    }
    protected putOfFBS(url, body) {
        const newUrl = this.fbsAddress + url;
        return this.Put(newUrl, body);
    }
    protected postOfFBS(url, body) {
        const newUrl = this.fbsAddress + url;
        return this.Post(newUrl, body);
    }
    /**
     * @param  {string} url
     * @param  {} params 
     */
    protected PostCloud(url: string, params) {
        // url = this.CloudHostName + url;
        let headers = new Headers();
        headers.append("boundApp", "mkitchen");
        return this.doPost(url, params, headers);
    }

    protected putCloud(url: string, params) {
        // url = this.CloudHostName + url;
        let headers = new Headers();
        headers.append("boundApp", "mkitchen");
        return this.doPut(url, params, headers);
    }

    private doPut(url: string, params, headers: Headers) {
        let result;
        headers.append("Content-Type", "application/json");
        if (this.Token)
            headers.append("token", this.Token);
        if (this.Terminal) {
            params.user = this.CurrentUser;
            params.terminal = this.Terminal;
        }
        result = (<any>this.http.put(url, JSON.stringify(params), { headers: headers })).toPromise();
        return this.ResultCallback(result);
    }

    protected GetCloud(url: string) {
        // url = this.CloudHostName + url;
        let result;
        result = (this.http.get(url) as any).toPromise();
        return this.ResultCallback(result);
    }

    private doPost(url: string, params, headers: Headers) {
        let result;
        headers.append("Content-Type", "application/json");
        if (this.Token)
            headers.append("token", this.Token);
        if (this.Terminal) {
            params.user = this.CurrentUser;
            params.terminal = this.Terminal;
        }
        result = (<any>this.http.post(url, JSON.stringify(params), { headers: headers })).toPromise();
        return this.ResultCallback(result);
    }

    /**
     * 
     * @param url
     * @param sucb
     * @param errcb
     */
    protected Get(url: string, port?: number) {
        let result;
        result = (this.http.get(url) as any).toPromise();
        return this.ResultCallback(result);
    }
    /**
     * 
     * @param url
     * @param params
     * @param sucb
     * @param errcb
     */
    protected Put(url: string, params): Promise<any> {
        let result;
        let headers = new Headers();
        headers.append("Content-Type", "application/json");
        headers.append("token", this.Token);
        headers.append("storeId", this.CurrentStore.id);
        if (this.Terminal) {
            params.user = this.CurrentUser;
            params.terminal = this.Terminal;
        }
        result = (<any>this.http.put(url, JSON.stringify(params), { headers: headers })).toPromise();

        return this.ResultCallback(result);
    }

    protected Jsonp(url: string, params) {
        url = this.CloudHostName + url;
        (<any>this.jsonp.get(url, { search: params })).toPromise();

        return new Promise((resolve, reject) => {
            EventRegistHandle.RegistHandle("jsonpHandle", (data) => {
                EventRegistHandle.RemoveHandle("jsonpHandle");
                if (data.result != undefined && data.result == false) {
                    reject(data.msg);
                }
                else {
                    resolve(data);
                }

            });
        });
    }

    private ResultCallback(result): Promise<any> {
        return new Promise((resolve, reject) => {

            result.then(data => {
                //有些api接口没有返回，先这样子 todo
                if (!data._body) {
                    return resolve(data._body);
                }
                if (data.ok) {
                    let rData = data.json();
                    /*判断rData是否满足标准的格式，如果不是标准的格式
                    * 如果不是标准的格式则是来自数据同步老接口返回
                    */
                    if (this.IsOldAPIResult(rData)) {
                        if (rData.code == 200) resolve(rData.data);
                        else reject(rData.message);
                    }
                    else resolve(rData);
                }
                else reject(data.json().message);
            }).catch(err => {
                reject("连接本地数据中心错误");
            })
        });
    }

    private IsOldAPIResult(data): boolean {
        let checkPnts = [false, false, false];
        if (data.code != null && data.code != undefined) checkPnts[0] = true;
        if (data.code) {
            if (data.code == 200) {
                if (data.data) return true;
                else return false;
            }
            else {
                if (data.message) return true;
                else return false;
            }
        }
        else return false;
    }
}

